package com.longcai.cm.api.upload;

import com.alibaba.fastjson.JSONObject;
import com.longcai.cm.base.baidu.ueditor.ActionEnter;
import com.longcai.cm.base.config.UeditorConfig;
import com.longcai.cm.utils.DateUtils;
import com.longcai.cm.utils.FileUtil;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/ueditor")
public class UeditorController {


    @Value("${lcmaster.upload.systemUploadPath}")
    private String systemUploadPath;

    @RequestMapping("/config")
    public void uEditorConfig(HttpServletRequest request, HttpServletResponse response, String callback, String action) throws IOException {

        response.setContentType("text/html; charset=UTF-8");
        PrintWriter writer = response.getWriter();

        try {
            switch (action) {
                // 此处即为获取配置文件的case
                case "config":
                    String myresult = UeditorConfig.CONFIG.getConfigStr(callback);
                    writer.write(myresult);
                    writer.close();
                    break;
                case "uploadimage":
                    JSONObject json = new JSONObject();
                    json.put("state", "SUCCESS");
                    json.put("success", true);
                    json.put("original", "1.jpg");
                    json.put("size", "1212");
                    json.put("url", "http://127.0.0.1:4002/CM//upload/2019-12-31/2019-12-313787.jpg");
                    json.put("title", "222");
                    json.put("type", ".jpg");
                    json.put("code", 0);
                    writer.write(json.toString());
                    writer.close();
                    break;
                default:
                    break;
            }

        } catch (Exception e) {
            // TODO: handle exception
        }

    }


    @RequestMapping(value = "/config2")
    public void config(HttpServletRequest request, HttpServletResponse response) throws JSONException {
//        String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        String rootPath = "/home/java/farmbank";
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            System.err.println(exec);
            // TODO: 2024/6/29 保存图片到commonImg
            /*
             * 单个图片上传
             * {
             * "state": "SUCCESS",
             * "original": "\u4f01\u4e1a\u5fae\u4fe1\u622a\u56fe_17152430617146.png",
             * "size": "21671","title": "1719646045393026429.png","type": ".png",
             * "url": "/LCMaster/upload/20240629/1719646045393026429.png"
             * }
             */
//            final ZImgTmp one = imgTmpService.getById("000000");
//            if (exec.contains("list") && exec.contains("url")) {
//                final JSONObject execJson = JSON.parseObject(exec);
//                final List<JSONObject> array = execJson.getJSONArray("list");
//                for (JSONObject jsonObject : array) {
//                    String source = DomainConfig.LOCALHOST + jsonObject.getString("url");
//                    final WxMediaImgUploadResult result = wxMpService.getMaterialService().mediaImgUpload(jsonObject.getObject("file", File.class));
//                    commonImgService.save(new ZCommonImg(
//                            StringUtil.getUuid(), result.getUrl(), source,
//                            one.getValue(), DateUtil.now()
//                            )
//                    );
//                }
//            }
//            if (!exec.contains("list") && exec.contains("url")) {
//                final JSONObject jsonObject = JSON.parseObject(exec);
//                String source = DomainConfig.LOCALHOST + jsonObject.getString("url");
//                final WxMediaImgUploadResult result = wxMpService.getMaterialService().mediaImgUpload(jsonObject.getObject("file", File.class));
//                commonImgService.save(new ZCommonImg(
//                        StringUtil.getUuid(), result.getUrl(), source,
//                        one.getValue(), DateUtil.now()
//                        )
//                );
//            }
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 文件上传
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> resultMap = new HashMap<>();

        try {
            // 上传文件保存路径
            String uploadPath = systemUploadPath;
            String dateStr = DateUtils.getTodayStr();
            String descFileDir = uploadPath + "upload/" + dateStr;

            FileUtil.mkdirs(descFileDir);

            String dataString = "";

            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            Iterator<String> iterator = req.getFileNames();
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                String fileNames = file.getOriginalFilename();
                int split = fileNames.lastIndexOf(".");
                //存储文件
                //文件名  fileNames.substring(0,split)
                //文件格式   fileNames.substring(split+1,fileNames.length())
                //文件内容 file.getBytes()
                //file.getInputStream()

                String newFileName = DateUtils.getTodayStr() + new Random().nextInt(10000) + fileNames.substring(fileNames.lastIndexOf("."), fileNames.length());
                InputStream is = file.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                OutputStream out = new FileOutputStream(descFileDir + "/" + newFileName);
                while ((len = is.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.close();
                is.close();
                dataString = "/upload/" + dateStr + "/" + newFileName;
            }
            resultMap.put("state", "success");
            resultMap.put("path", dataString);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("state", "fail");
        }

        return resultMap;

    }

}
